package com.mingqijia.gassafety.job.hangzhou.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mingqijia.gassafety.db.entity.HistoryAlarm;
import com.mingqijia.gassafety.db.hangzhou.entity.DeviceDataReport;
import com.mingqijia.gassafety.db.hangzhou.entity.ThingModelProperty;
import com.mingqijia.gassafety.db.hangzhou.mapper.CityDeviceMapper;
import com.mingqijia.gassafety.db.hangzhou.mapper.DeviceDataReportMapper;
import com.mingqijia.gassafety.db.hangzhou.mapper.ThingModelOutputDataMapper;
import com.mingqijia.gassafety.db.hangzhou.mapper.ThingModelPropertyMapper;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConfiguration;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.HistoryAlarmMapper;
import com.mingqijia.gassafety.job.hangzhou.request.CityDeviceDataRequest;
import com.mingqijia.gassafety.job.hangzhou.request.SetCityDeviceData;
import com.mingqijia.gassafety.job.hangzhou.response.HzResponse;
import com.mingqijia.gassafety.job.hangzhou.service.impl.HangZhouServiceImpl;
import com.mingqijia.gassafety.job.hangzhou.service.impl.SetCityDeviceDataServiceImpl;
import com.mingqijia.gassafety.job.request.ConsumerListRequest;
import com.mingqijia.gassafety.job.response.ConsumerResponse;
import com.mingqijia.gassafety.job.service.ConsumerService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.EquipmentTypeConst;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangfei
 */
@Configuration
@EnableScheduling
//@ConditionalOnProperty(name = "hangzhou.scheduling.enabled", havingValue = "true")
@Slf4j
public class SetCityDeviceDataJob {
    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    HangZhouServiceImpl hangZhouService;
    @Autowired
    CityDeviceMapper cityDeviceMapper;
    @Autowired
    ThingModelPropertyMapper propertyMapper;
    @Autowired
    ThingModelOutputDataMapper outputDataMapper;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    InfluxDBConfiguration influxDBConnect;
    @Autowired
    DeviceDataReportMapper deviceDataReportMapper;
    @Autowired
    SetCityDeviceDataServiceImpl setCityDeviceDataServiceImpl;
    @Value("${gassafety.hangzhou.yhSpId}")
    private String hangzhouSpId;

    @Autowired
    HistoryAlarmMapper historyAlarmMapper;

    @Autowired
    DtuMapper dtuMapper;

    /**
     * 预警数据上报 0 0/1 * * * ?
     */
    @Scheduled(cron = "${gassafety.job.hangzhou.setCityDeviceData}")
    public void setCityDeviceDataJob() {
        log.info("setCityDeviceDataJob--start--------");
        //防重复锁
        String key = Constants.SET_CITYDEVICEDATA;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                //查询当天 余杭设备 最近两小时的最新一条报警信息
                List<HistoryAlarm> newAlarmList = historyAlarmMapper.selectListTwoHours(hangzhouSpId);

                List<String> imeis = newAlarmList.stream().map(HistoryAlarm::getIMEI).collect(Collectors.toList());
                log.info("需要推送的imei号:{}", JSONObject.toJSONString(imeis));


                // city_device 关联dtu获得的信息
                if (CollectionUtil.isEmpty(imeis)) {
                    return;
                }
                //获取设备及对应客户信息
                List<Map<String, Object>> list= dtuMapper.selectRelation(imeis);
                if (CollectionUtil.isEmpty(list)) {
                    return;
                }
                //获取 对应客户信息
                List<ConsumerResponse> consumers = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    Integer consumerId = StringUtils.isEmpty(map.get("ConsumerId"))
                            ? 0 : Integer.parseInt(map.get("ConsumerId") + "");
                    String spId = StringUtils.isEmpty(map.get("tSpId"))
                            ? "-" : map.get("tSpId") + "";
                    // 获取 设备dtu对应的客户信息
                    ConsumerListRequest consumerListRequest = new ConsumerListRequest();
                    List<Integer> consumerIds = new ArrayList<>();
                    consumerIds.add(consumerId);
                    consumerListRequest.setConsumerIdList(consumerIds);
                    consumerListRequest.setSpId(spId);
                    List<ConsumerResponse> consumerList = consumerService.consumerList(consumerListRequest).getList();
                    ConsumerResponse consumerResponse = consumerList.get(0) == null ? new ConsumerResponse() : consumerList.get(0);
                    ConsumerResponse response = new ConsumerResponse();
                    response.setId(consumerResponse.getId());
                    response.setContactsName(consumerResponse.getContactsName());
                    response.setContactsTelephone(consumerResponse.getContactsTelephone());
                    consumers.add(response);

                }


                //将数据推送给本地化
                CityDeviceDataRequest request = new CityDeviceDataRequest();
                request.setNewAlarmList(newAlarmList);
                request.setConsumers(consumers);
                request.setList(list);

                hangZhouService.setCityDeviceData(request);
                log.info("setCityDeviceDataJob--end--------");


            }
        } catch (Exception e) {
            log.info("setCityDeviceDataJob-error:{}", e);
        } finally {
            redisUtil.del(key);
        }
        log.info("setCityDeviceDataJob--end--------");

    }


    /**
     * <p>
     * 普通数据上报，一天一次
     */
    @Scheduled(cron = "${gassafety.job.hangzhou.setCityDeviceGeneralData}")
    public void setCityDeviceGeneralDataJob() {
        log.info("setCityDeviceGeneralDataJob--start--------");
        //防重复锁
        String key = Constants.SET_CITYDEVICEGENERALDATA;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {

                if (setCityDeviceDataServiceImpl.execute()) return;
            }
        } catch (Exception e) {
            log.info("setCityDeviceGeneralDataJob-error:{}", e);
        } finally {
            redisUtil.del(key);
        }
        log.info("setCityDeviceGeneralDataJob--end--------");

    }



}
